package com.jyh.homework5;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author JYH
 * @Date 2024/8/7 17:12
 * @Description 设计一个多线程的程序如下：设计一个火车售票模拟程序。
                假如火车站要有100张火车票要卖出，现在有5个售票点同时售票，用5个线程模拟这5个售票点的售票情况。
 */
public class HW1 {
    public static void main(String[] args) {
        sale sale = new sale();
        new Thread(sale,"窗口1").start();
        new Thread(sale,"窗口2").start();
        new Thread(sale,"窗口3").start();
        new Thread(sale,"窗口4").start();
        new Thread(sale,"窗口5").start();

    }
}

class sale implements Runnable {
    Lock lock=new ReentrantLock();
    private int ticketNum = 100;

    @Override
    public void run() {
      while (true){
          try {
              lock.lock();
              if (ticketNum<=0){
                  break;
              }
              try {
                  Thread.sleep(100);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
              System.out.println(Thread.currentThread().getName()+"正在卖第"+ticketNum+"张票");
              ticketNum--;
          } catch (Exception e) {
              e.printStackTrace();
          } finally {
              lock.unlock();
          }
      }
        System.out.println("票卖完了");
    }
}
